const echarts = require('../../ec-canvas/echarts');

// 工具函数：深度比较两个对象是否相等
const deepEqual = (a, b) => {
    if (a === b) return true;
    if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;
    const keysA = Object.keys(a),
        keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;
    return keysA.every(key => keysB.includes(key) && deepEqual(a[key], b[key]));
};

Component({
    properties: {
        // 父组件传入的配置
        ecConfig: {
            type: Object,
            value: null,
            observer(newConfig, oldConfig) {
                if (!this.chart) {
                    console.error('[ECharts Wrapper] 图表未初始化，跳过更新！');
                    return;
                }
                if (!deepEqual(newConfig, oldConfig)) {
                    this.updateChart(newConfig); // 更新图表配置
                }
            },
        },
    },

    lifetimes: {
        attached() {
            console.log('[ECharts Wrapper] 组件已附加，初始化图表...');
            this.initChart(); // 初始化图表
        },

        detached() {
            console.log('[ECharts Wrapper] 组件已卸载，销毁图表...');
            this.disposeChart(); // 销毁图表
        },
    },

    methods: {
        // 初始化图表
        initChart() {
            const canvasComp = this.selectComponent('#canvas');
            if (!canvasComp) {
                console.error('[ECharts Wrapper] 找不到 canvas 组件！');
                return;
            }

            canvasComp.init((canvas, width, height, dpr) => {
                this.chart = echarts.init(canvas, null, {
                    width,
                    height,
                    devicePixelRatio: dpr,
                });

                canvas.setChart(this.chart);
                console.log('[ECharts Wrapper] 图表实例初始化成功！');

                // 应用传入的初始配置
                if (this.data.ecConfig) {
                    this.chart.setOption(this.data.ecConfig);
                }
            });
        },

        // 更新图表配置
        updateChart(newConfig) {
            console.log('[ECharts Wrapper] 更新图表配置...', newConfig);
            try {
                if (this.chart) {
                    this.chart.setOption(newConfig, true); // 渲染配置
                }
            } catch (err) {
                console.error('[ECharts Wrapper] 更新失败：', err);
            }
        },

        // 销毁图表
        disposeChart() {
            if (this.chart) {
                console.log('[ECharts Wrapper] 销毁图表实例...');
                this.chart.dispose();
                this.chart = null; // 移除对图表的引用
            }
        },
    },
});